import "./Login.css";
import { useState } from "react";
import axios from "../axios";
import userStore from "../stores/UserStore";
import { useNavigate } from "react-router-dom";
import { Button } from "antd";
import { Link } from 'react-router-dom';

function Login() {
    const navigate = useNavigate();
    const [account, setAccount] = useState("");
    const [password, setPassword] = useState("");

    const onLogin = async () => {
        if (!account || !password) {
            alert('请填入账号密码');
            return;
        }
        const res = await axios.post("/users/login", { account: account, pwd: password });
        try {
            if (res.data && res.data.code === 2000) {
                userStore.login(res.data.data.user, res.data.data.jwttoken ,60 * 60 * 1000); // 30 分钟后自动注销
                alert(res.data.msg);
                navigate("/home");
            } else {
                alert(res.data.msg);
            }
        }catch (error) {
            if (error.response) {
                alert(error.response.data.msg);
            } else if (error.request) {
                alert('请求超时，请稍后再试');
            } else {
                alert('请求失败，请稍后再试');
            }
        }
    };

    return (
        <div className="login-container">
            <div className="login-form">
                <h1>登录</h1>
                <div className="login-title">欢迎使用宠物领养平台</div>
                <input
                    type="text"
                    placeholder="请输入账号"
                    value={account}
                    onChange={(e) => setAccount(e.target.value)}
                />
                <input
                    type="password"
                    placeholder="请输入密码"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                />
                <Button type="primary" onClick={onLogin}>登录</Button>
                <div className="register-link">
                    还没有账号? <Link to="/reg">点此注册</Link>
                </div>
            </div>
        </div>
    );
}

export default Login;